package com.google.ideas.MobileMeme;

import com.google.ideas.MobileMeme.meme.BaseImage;
import com.google.ideas.MobileMeme.meme.ImageStore;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NavUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

// TODO(lally): Make this a regular Activity.
public class StreamListActivity extends FragmentActivity implements StreamListManager.Callbacks {

  private static final String STREAM_LIST_ACTIVITY = "stream_list_activity";
  private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

  private ImageStore store_;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stream_twopane);
    // Disable the Home button on our action bar.
    getActionBar().setDisplayHomeAsUpEnabled(false);

    Log.d(STREAM_LIST_ACTIVITY, "Initializing the StreamListActivity.");
    
    // We need an ImageStore to hold pictures we take.
    store_ = new ImageStore(this);

    if (findViewById(R.id.twopane_frame_layout) != null) {
      if (savedInstanceState != null) {
        // don't bring up a new one -- we're being restored.
        return;
      }
      // Set up the list of streams
      StreamListFragment list_of_streams = new StreamListFragment();
      FragmentTransaction xact = getSupportFragmentManager().beginTransaction();
      xact.add(R.id.twopane_frame_layout, list_of_streams);
      xact.commit();
    }
  }
  
  @Override
  public void onStart() {
    super.onStart();
  }
  
  /*
   * See if we've set up the StreamListManager yet. If not, do so. We do it 
   * here instead of onCreate on the theory that we have to wait for the 
   * fragment transaction to finish first.
   */
  @Override
  protected void onResume() {
    super.onResume();
  }


  private File getPhotoTempFile() {
    final File path = new File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
          + File.separator + getPackageName());
    if (!path.exists()) {
      Log.i(STREAM_LIST_ACTIVITY, "getPhotoTempFile: " + path + " does not exist.  Creating");
      
      boolean res = path.mkdirs();
      if (!res) {
        Log.e(STREAM_LIST_ACTIVITY, "getPhotoTempFile: could not create!!");
      }
    }
    File retval = new File(path, "photo.tmp");
    Log.i(STREAM_LIST_ACTIVITY, "getPhotoTempFile: returning " + retval);
    return retval;
  }
  
  public void takeAPicture() {
    // Note: we only get a preview in the "data" part of the Bundle.
    // If I give a filename, I get the real image in that file.

    // Create Intent to take a picture and return control to the calling
    // application
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        
    // Tell it where to save the photo.
    File tmp = getPhotoTempFile();
    if (tmp == null) {
      Toast.makeText(this, "Failed to find a place to put the picture", 
          Toast.LENGTH_LONG).show();
      return;
    }
    intent.putExtra(MediaStore.EXTRA_OUTPUT, 
                    Uri.fromFile(tmp));
    // start the image capture Intent
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}

/* Process results from any activities we've run.  Namely, the camera app. 
 * @see android.support.v4.app.FragmentActivity#onActivityResult(int, int, android.content.Intent)
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  if (requestCode ==  CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
    if (resultCode == RESULT_OK) {
      try {
        File tmp = getPhotoTempFile();
        Bitmap imagedata = Media.getBitmap(getContentResolver(), Uri.fromFile(tmp));
        // we don't need to calculate the hash here, the ImageStore will do that for us.
        BaseImage image = new BaseImage("IMG_" + imagedata.hashCode(), imagedata, null);
        String hash = store_.saveImage(store_.getWritableDatabase(), image);
        image.setHash(hash);
        imagedata.setDensity(DisplayMetrics.DENSITY_DEFAULT);
        int width = imagedata.getWidth();
        int height = imagedata.getHeight();
        Log.i(STREAM_LIST_ACTIVITY, "Saved a ("+width+"x"+height+") image: " + image);
        tmp.delete();
        Toast.makeText(this, "Your picture is ready to use for a meme!", 
            Toast.LENGTH_SHORT).show();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else if (resultCode != RESULT_CANCELED) {
      Log.e(STREAM_LIST_ACTIVITY, "Got error " + resultCode 
          + " when trying to take a picture.");
      Toast.makeText(this, "Sorry, got an error when trying to take a picture (" 
          + resultCode + ")", Toast.LENGTH_LONG).show();
    }
  } else {
    super.onActivityResult(requestCode, resultCode, intent);
  }
}
  
  public void makeAMeme() {
    Log.d(STREAM_LIST_ACTIVITY, "Making a meme...");
    Intent launch = new Intent(this, ViewTemplates.class);
    startActivity(launch);
  }

  /*
   * Set up a menu.
   *
   * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
   */
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.toplevel, menu);
    return super.onCreateOptionsMenu(menu);
  }
  /** Handle menu selections */
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
      case R.id.take_picture:
        takeAPicture();
        return true;
    }
    return super.onOptionsItemSelected(item);
  }

  /** Handle selections from our list of streams */
  @Override
  public void onItemSelected(String id) {
    Bundle arguments = new Bundle();
    arguments.putString(StreamDetailFragment.ARG_ITEM_ID, id);
    StreamDetailFragment fragment = new StreamDetailFragment();
    fragment.setArguments(arguments);
    Log.d(STREAM_LIST_ACTIVITY, "item '" + id + "' selected.  Trying a slide.");
    getSupportFragmentManager()
        .beginTransaction()
        .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left,
            R.anim.slide_in_from_left, R.anim.slide_out_to_right)
        .replace(R.id.twopane_frame_layout, fragment)
        .addToBackStack(null)
        .commit();
  }
}
